package com.songmao.pricecloudapitest.socket.tcp;

import com.alibaba.fastjson.JSON;

import com.songmao.pricecloudapitest.socket.entity.tcp.EncryptionEntity;
import com.songmao.pricecloudapitest.socket.entity.tcp.ResponseTcpEntity;
import com.songmao.pricecloudapitest.socket.entity.tcp.UserEntity;
import com.songmao.pricecloudapitest.utils.ParsingJson;

import java.io.*;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

/**
 * @author Remy
 * @description :
 * @date 2020-04-22 17:25
 */
public class TcpClientGetQuote {
    private static int count = 1;

    private static Socket socket;

    private static DataInputStream dis;

    private static Long timeStamp = System.currentTimeMillis() / 1000;

    private static String md5() {
        String version = "1.0.0";
        String secretKey = "htrh6)(4j5345#jkld";
        String dataType = "0";
        String s = timeStamp.toString();
        String keys = dataType + s + version + secretKey;

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(keys.getBytes());
            byte[] encryContext = md.digest();

            int i;
            StringBuilder buf = new StringBuilder();
            //做相应的转化（十六进制）
            for (byte b : encryContext) {
                i = b;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            // 32位的加密
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static Socket createConnectionTcp() throws IOException {
        String key = md5();
        EncryptionEntity entity = EncryptionEntity.builder().dataType(0).dataTime(System.currentTimeMillis() / 1000).version("1.0.0").data(
                UserEntity.builder().username("client").password("1MmH0AfGWnzd").depth(10).build()
        ).key(key).build();
        String json = JSON.toJSONString(entity);
        StringBuilder stringBuffer;
        stringBuffer = new StringBuilder(json).insert(0, "W");
        stringBuffer.insert(stringBuffer.length(), "QUIT");
        System.out.println(stringBuffer.toString());

        if (count == 1) {
            socket = new Socket("192.168.1.203", 12960);
            //2.获取输出流，向服务器端发送信息
            //字节输出流
            OutputStream os = socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(stringBuffer.toString());
            count++;
            return socket;
        }
        return socket;
    }

    /**
     * 调用此方法获取报价;
     * @return：ResponseTcpEntity
     */
    public static ResponseTcpEntity getSymbolQuote() {
        try {
            if (count == 1) {
                Socket socket = createConnectionTcp();
                InputStream is = socket.getInputStream();
                dis = new DataInputStream(is);
            }
            String temp = dis.readUTF();
            String[] temps = temp.split("QUITW");
            for (String s : temps) {
                Object type = ParsingJson.getPathCode(s, "/data_type");
                Optional<Object> optional = Optional.ofNullable(ParsingJson.getPathCode(s, "/data_type"));

                if (optional.isPresent()) {
                    assert type != null;
                    if (Integer.parseInt(type.toString()) == 2) {
                        return JSON.parseObject(s, ResponseTcpEntity.class);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void main(String[] args) {
        while(true){
            System.out.println( getSymbolQuote());
        }
    }

}
